package com.jinke.api.component;

import com.plexpt.chatgpt.ChatGPT;
import com.plexpt.chatgpt.entity.chat.ChatCompletion;
import com.plexpt.chatgpt.entity.chat.ChatCompletionResponse;
import com.plexpt.chatgpt.entity.chat.Message;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Slf4j
public class OpenAI {

    @Autowired
    private ChatGPT chatGPT;

    private final static Logger logger = LoggerFactory.getLogger(OpenAI.class);


    public String asyncSend(String prompt) {
        // 获取上下文
        try {

            Message system = Message.ofSystem("提取出这些属性转成json,不要换行:personName,addressLine1,city,stateCode,zipCode,phone");
            Message message = Message.of(prompt);

            ChatCompletion chatCompletion = ChatCompletion.builder()
                    .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                    .messages(Arrays.asList(system, message))
                    .maxTokens(3000)
                    .temperature(0.9)
                    .build();
            ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
            Message res = response.getChoices().get(0).getMessage();
            String content = res.getContent();
            log.info("send==> "+prompt);
            log.info("rec==> "+content);
            return content;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ChatGPT Exception: " + e.getMessage());
        }
        return "";
    }
}
